package com.borened.netty.protocol.mqtt;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MqttBroker implements InitializingBean {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Map<String, MqttClientSession> clients;
    private int port;


    @Resource
    private MqttMessageHandler mqttMessageHandler;

    @Override
    public void afterPropertiesSet() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        clients = new HashMap<>();
    }
    public void start(int port) {
        this.port = port;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new MqttDecoder())
                                .addLast(mqttMessageHandler)
                                .addLast(MqttEncoder.INSTANCE)
                               ;
                    }
                });
        try {
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("MQTT broker started on port:{} " , port);
            //同步等待服务端监听端口关闭
            //future.channel().closeFuture().sync();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
    @PreDestroy
    public void destroy() {
        log.info("MQTT broker stopped");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    public Map<String, MqttClientSession> getClients() {
        return clients;
    }

    public void addClient(MqttClientSession client) {
        clients.put(client.getClientId(), client);
        prettyPrintClients();
    }
    public void removeClient(MqttClientSession client) {
        clients.remove(client.getClientId());
        prettyPrintClients();
    }

    private void prettyPrintClients() {
        StringBuilder msg = new StringBuilder("当前连接客户端:\n");
        for (MqttClientSession client : clients.values()) {
            msg.append(client.toString()).append("\n");
        }
        log.info(msg.toString());
    }


}
